﻿/*********************************************
 创建者：  george
 创建时间：2017-06-10
 功能说明：天气处理程序
 ********************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using WeatherAPI.Helper;
using WeatherAPI.Model;
using com.nm.Helper;
using george.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WeatherAPI
{
    [Description("返回城市天气信息")]
    public class WeatherHandler:BaseHandler
    {
        [MustLogin]
        [Description("返回城市天气列表")]
        [ReturnType(typeof(PaperData<WeatherList>))]
        public ApiResult GetCityWeatherList([ParamDescription("城市代码或名称")] string key = "", 
            [ParamDescription("页码")]int Page = 1,
            [ParamDescription("页数")]int Size = 10)
        {
            var dc = new WeatherEntities();
            var forecastType=((int) WeatherHelper.BigDataType.forecast).ToString();
            var observeType = ((int) WeatherHelper.BigDataType.observe).ToString();
            var query = (from wd in dc.vm_forecast_observe_Data
                join ct in dc.w_dt_citys on wd.areaId equals ct.areaId
                group wd by new {ct.areaId, ct.areaName, wd.createDate}
                into p
                select new
                {
                    p.Key,
                    forecast = (from f in dc.vm_forecast_observe_Data
                        where f.bigDataType == forecastType
                              && p.Key.areaId == f.areaId
                        select f).ToList(),
                    observe = (from o in dc.vm_forecast_observe_Data
                        where o.bigDataType == observeType
                              && p.Key.areaId == o.areaId
                        select o).FirstOrDefault()
                });
            if (!string.IsNullOrWhiteSpace(key))
                query = query.Where(t => t.Key.areaId.Contains(key) || t.Key.areaName.Contains(key));
            var result = PaperData<WeatherList>.Create(query.Count(), Size, Page);
            result.Items = query.OrderBy(t=>t.Key.areaId).Skip(result.Skip)
                    .Take(result.Limt).ToList().Select(x => new WeatherList()
            {
                AreaId = x.Key.areaId,
                AreanName = x.Key.areaName,
                WeatherDateTime = Convert.ToDateTime(x.Key.createDate),
                Week = WeatherHelper.DayOfWeek(Convert.ToDateTime(x.Key.createDate)),
                forecastDetail = x.forecast.Select(f => new WeatherList.WeatherDetail
                {
                    DataType = f.bigDataType,
                    Sequence = f.sequence,
                    resultList = GetWeatherDetail(f.bigDataType, f.dataValue)
                }).ToList(),
                observeDetail =new WeatherList.WeatherDetail
                {
                    DataType = x.observe.bigDataType,
                    Sequence = x.observe.sequence,
                    resultList = GetWeatherDetail(x.observe.bigDataType, x.observe.dataValue)
                }
            }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("返回城市天气")]
        [ReturnType(typeof(WeatherList))]
        public ApiResult GetIpWeatherList([ParamDescription("城市名称")]string key="")
        {
            string city;
            if (!string.IsNullOrWhiteSpace(key))
            {
                city = key;
            }
            else
            {
                var ipCity = IpHelper.IPGetCity();
                city = ipCity == "" ? "广州" : ipCity;
            }
            var dc = new WeatherEntities();
            var forecastType = ((int)WeatherHelper.BigDataType.forecast).ToString();
            var observeType = ((int)WeatherHelper.BigDataType.observe).ToString();
            var query = (from wd in dc.vm_forecast_observe_Data
                         join ct in dc.w_dt_citys on wd.areaId equals ct.areaId
                         where city.Contains(ct.areaName)
                         group wd by new { ct.areaId, ct.areaName, wd.createDate }
                into p
                         select new
                         {
                             p.Key,
                             forecast = (from f in dc.vm_forecast_observe_Data
                                         where f.bigDataType == forecastType
                                               && p.Key.areaId == f.areaId 
                                         select f).ToList(),
                             observe = (from o in dc.vm_forecast_observe_Data
                                        where o.bigDataType == observeType
                                              && p.Key.areaId == o.areaId
                                        select o).FirstOrDefault()
                         });
           var result = query.ToList().Select(x => new WeatherList()
                    {
                        AreaId = x.Key.areaId,
                        AreanName = x.Key.areaName,
                        WeatherDateTime = Convert.ToDateTime(x.Key.createDate),
                        Week = WeatherHelper.DayOfWeek(Convert.ToDateTime(x.Key.createDate)),
                        forecastDetail = x.forecast.Select(f => new WeatherList.WeatherDetail
                        {
                            DataType = f.bigDataType,
                            Sequence = f.sequence,
                            resultList = GetWeatherDetail(f.bigDataType, f.dataValue)
                        }).ToList(),
                        observeDetail = new WeatherList.WeatherDetail
                        {
                            DataType = x.observe.bigDataType,
                            Sequence = x.observe.sequence,
                            resultList = GetWeatherDetail(x.observe.bigDataType, x.observe.dataValue)
                        }
                    }).ToList();
            return Success(result);
        }
        /// <summary>
        /// 解析天气数据
        /// </summary>
        /// <param name="dataType">数据类型</param>
        /// <param name="DataValue">数据</param>
        /// <returns></returns>
        List<WeatherList.ResultList> GetWeatherDetail(string dataType,string DataValue)
        {
            if (string.IsNullOrWhiteSpace(DataValue) || string.IsNullOrWhiteSpace(dataType))
                return null;
            var jsonStr = (JObject)JsonConvert.DeserializeObject(DataValue);
            var list = new List<WeatherList.ResultList>();
            foreach (var item in jsonStr)
            {
                var imgUrl = "/upfile/weather/";
                var itemValue = item.Value.ToString();
                var wind = WeatherHelper.WindDirection().FirstOrDefault(t => t.keys == itemValue);
                if (string.IsNullOrWhiteSpace(itemValue))
                    imgUrl = imgUrl + "Cloudy.png";
                else
                {
                    imgUrl = imgUrl + wind?.EnName+".png";
                }
                 var rows = new WeatherList.ResultList
                {
                    Keys = WeatherHelper.InitDataType()
                        .FirstOrDefault(t => t.DataType == dataType && t.SmallCode == item.Key)?.ChinaeseName,
                    Values =
                        dataType == ((int) WeatherHelper.BigDataType.forecast).ToString()
                            ? "001,002".Contains(item.Key)
                                ? WeatherHelper.WindDirection()
                                    .FirstOrDefault(t => t.keys == itemValue)?.values
                                : itemValue
                            : itemValue,
                    imgUrl = dataType == ((int) WeatherHelper.BigDataType.forecast).ToString()
                        ? "001,002".Contains(item.Key)
                            ? ImageHelper.GetImageUrl(imgUrl, "http")
                            : ""
                        : ""
                };
                list.Add(rows);
            }
            return list;
        }

        [MustLogin]
        [Description("返回城市列表")]
        [ReturnType(typeof(IList<w_dt_citys>))]
        public ApiResult GetCityList()
        {
            var dc = new WeatherEntities();
            var result = dc.w_dt_citys.ToList().Select(t => new w_dt_citys()
            {
                areaId = t.areaId,
                areaName = t.areaName,
                parentId = t.parentId
            }).ToList();
            return Success(result);
        }
    }
}
